package com.onenine.app.view.dialog;

import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatDialog;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.onenine.app.R;
import com.onenine.app.model.AppUpdateItem;
import com.onenine.app.service.DownloadService;
import com.onenine.app.utils.AppUpdateUtils;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.base.utils.Toasty;
import com.onenine.common.util.ApUtils;

import java.io.File;

/**
 * 版本升级弹窗
 */
public class AppUpdateDialog extends AppCompatDialog implements View.OnClickListener {

    private Context mContext;
    private TextView mTvTitle, mTvApkSize, mTvContent;
    private Button mBtnCancel, mBtnConfirm;
    private ProgressBar mProgressBar;
    private AppUpdateItem mUpdateItem;
    private TextView mvProValue;
    private DownloadService.DownloadBinder mDownloadBinder;

    public AppUpdateDialog(Context context, AppUpdateItem updateItem) {
        super(context, R.style.DialogStyle);
        mContext = context;
        mUpdateItem = updateItem;
        initView();
        loadData();
    }

    private void initView() {
        setCancelable(false);
        setCanceledOnTouchOutside(false);
        View view = LayoutInflater.from(mContext)
                .inflate(R.layout.layout_app_update_dialog, null);
        setContentView(view);
        int roleColor = RoleResLoader.getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR);
        mTvTitle = view.findViewById(R.id.tv_title);
        mTvApkSize = view.findViewById(R.id.tv_apk_size);
        mTvContent = view.findViewById(R.id.tv_content);
        mProgressBar = view.findViewById(R.id.pb_download);
        mProgressBar.setProgressDrawable(ActivityCompat.getDrawable(mContext
                , RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.HORIZONTAL_PROGRESS_BAR_BG)));
        mvProValue = view.findViewById(R.id.tv_progress_value);
        mvProValue.setTextColor(RoleResLoader.getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR));
        mBtnCancel = view.findViewById(R.id.btn_cancel);
        mBtnCancel.setBackgroundResource(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.THEME_STROKE_WHITE_CORNER));
        mBtnCancel.setTextColor(roleColor);
        mBtnConfirm = view.findViewById(R.id.btn_confirm);
        mBtnConfirm.setBackgroundResource(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.THEME_GRADIENT_CORNER_BG));
    }

    /**
     * 加载数据
     */
    private void loadData() {
        mBtnCancel.setOnClickListener(this);
        mBtnConfirm.setOnClickListener(this);
        mTvTitle.setText(mContext.getString(R.string.find_new_version_hint, mUpdateItem.getVersionNum()));
        mTvApkSize.setText(mContext.getString(R.string.apk_size_hint, mUpdateItem.getPackageNum()));
        mTvContent.setText(mUpdateItem.getVersionDesc());
    }

    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            dismiss();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_cancel) {
            dismiss();
            if (mDownloadBinder != null) {
                DownloadService.unbindService(ApUtils.getApp(), conn);
                Toasty.showNormal(R.string.cancel_download_already);
                cancelDownloadService();
            }
        } else if (v.getId() == R.id.btn_confirm) {
            if (mDownloadBinder != null) {
                dismiss();
            } else {
                downloadApp();
            }
        }
    }

    /**
     * 开启下载
     */
    private void downloadApp() {
        //使用ApplicationContext延长他的生命周期
        DownloadService.bindService(ApUtils.getApp(), conn);
    }

    /**
     * 取消下载
     */
    private void cancelDownloadService() {
        if (mDownloadBinder != null) {
            // 标识用户已经点击了更新，之后点击取消
            mDownloadBinder.stop("取消下载");
            mDownloadBinder = null;
        }
    }

    /**
     * 回调
     */
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            startDownloadApp((DownloadService.DownloadBinder) service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    /**
     * 回调监听下载
     */
    private void startDownloadApp(DownloadService.DownloadBinder binder) {
        // 开始下载，监听下载进度，可以用对话框显示
        mDownloadBinder = binder;
        binder.start(mUpdateItem, new DownloadService.DownloadCallback() {
            @Override
            public void onStart() {
                if (AppUpdateDialog.this.isShowing()) {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mBtnCancel.setText(R.string.cancel_download);
                    mBtnConfirm.setText(R.string.download_background);
                }
            }

            @Override
            public void onProgress(float progress, long totalSize) {
                if (AppUpdateDialog.this.isShowing()) {
                    int value = Math.round(progress * 100);
                    mProgressBar.setProgress(value);
                    mvProValue.setText(value + "%");
                }
            }

            @Override
            public void setMax(long total) {

            }

            @Override
            public boolean onFinish(final File file) {
                if (AppUpdateDialog.this.isShowing()) {
                    AppUpdateUtils.installApp(mContext, file);
                }
                cancelDownloadService();
                dismiss();
                //一般返回 true ，当返回 false 时，则下载，不安装，为静默安装使用。
                return true;
            }

            @Override
            public void onError(String msg) {
                if (AppUpdateDialog.this.isShowing()) {
                    Toasty.showNormal("下载出错请重试");
                    cancelDownloadService();
                    mProgressBar.setVisibility(View.INVISIBLE);
                    mBtnCancel.setText(R.string.cancel);
                    mBtnConfirm.setText(R.string.update);
                }
            }

            @Override
            public boolean onInstallAppAndAppOnForeground(File file) {
                //这样做的目的是在跳转安装界面，可以监听到用户取消安装的动作;
                //activity.startActivityForResult(intent, REQ_CODE_INSTALL_APP);
                //但是如果 由DownloadService 跳转到安装界面，则监听失效。
                dismiss();
                cancelDownloadService();
                if (mContext != null) {
                    AppUpdateUtils.installApp(mContext, file);
                    //返回 true ，自己处理。
                    return true;
                } else {
                    //返回 flase ，则由 DownloadService 跳转到安装界面。
                    return false;
                }
            }
        });
    }

}
